import React, {Component} from 'react';
import {fetchAppraisal, getImageById} from '../../api/index';
import {ListView, Card, WingBlank, WhiteSpace, Flex, Modal, Grid} from 'antd-mobile';
import {setImageById} from '../../util/imageUtil';
import {calculateStatus as CalculateStatus} from '../../util/StateUtil';

interface Props {
    offset: number | null;
    limit: number | null;
    query: string;
    maxSize: number;
    coatBody?: React.ReactElement<any>;
    undershirtBody?: React.ReactElement<any>;
    history?: any;
    isCalendar?: boolean;
}

interface State {
    dataSource?: any;
    isLoading?: boolean;
    height?: number;
    hasMore?: boolean;
    dataArray: any[];
    limit: number;
    refreshing: boolean;
    offset: number;
    totalSize: number;
    query: string;
    isCalendar?: boolean;
}

function MyBody(props: any) {
    return <div style={{margin: '0px 5px 0px 5px'}}>{props.children}</div>;
}

function SmallBody(props: any) {
    return (
        <div style={{backgroundColor: '#ffffff'}} key={'ccc'}>
            {props.children}
        </div>
    );
}

async function loadingBatchImage(array: any) {
    return new Promise(async resolve => {
        const imageList = array;
        let resultList = []
        if (imageList.length > 0) {
            for (let i = 0; i < imageList.length; i++) {
                const item = imageList[i]
                let result: any = await getImageById(item);

                resultList.push({
                    icon: result.data.content,
                    text: `name${i}`,
                })
            }

        }
        resolve(resultList)
    })
}

class index extends Component<Props, State> {
    constructor(props: Props) {
        super(props);

        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1: any, row2: any) => row1 !== row2,
        });

        this.state = {
            offset: 0,
            refreshing: true,
            query: this.props.query || '(partyId == *) sortby metadata.createdDate/sort.descending',
            limit: 5,
            totalSize: 0,
            dataSource,
            isLoading: true,
            hasMore: true,
            dataArray: [],
            isCalendar: this.props.isCalendar || false,
        };
    }

    componentDidMount() {
    }

    // eslint-disable-next-line react/no-deprecated
    componentWillMount() {
        this.loadData();
    }

    componentWillReceiveProps(nextProps: any) {
        if (!!nextProps.query && this.props.query !== nextProps.query) {
            this.setState(
                {
                    dataArray: [],
                    query: nextProps.query,
                    limit: 5,
                    offset: 0,
                },
                () => {
                    this.loadData();
                }
            );
        }
    }

    loadData = () => {
        let then = this;
        let barcode = sessionStorage.getItem('barcode')
        if (!barcode) {
            return false;
        }
        const params = {
            offset: this.props.offset || this.state.offset * this.state.limit,
            limit: this.props.limit || this.state.limit,
            query: `( readerReserveGroup == *"barcode"*: *"${barcode}"* ) sortby metadata.createdDate/sort.descending`,
        };

        fetchAppraisal(params).then((response: any) => {
            const list = response.data.appraisalGroup;
            if (!!list) {
                const dataArr = this.state.dataArray.concat(list);

                let hasMore = true;
                if (dataArr.length >= response.data.totalRecords) {
                    hasMore = false;
                }
                dataArr.forEach(a => {
                    switch (a.state) {
                        case '0':
                            a.stateStr = '待审核';
                            break;
                        case '1':
                            a.stateStr = '已审核';
                            break;
                        case '2':
                            a.stateStr = '审核未通过';
                            break;
                        default:
                            a.stateStr = '';
                            break;
                    }
                })
                this.setState(
                    {
                        dataArray: dataArr,
                        totalSize: response.data.totalRecords,
                        isLoading: false,
                        hasMore, // 下拉刷新后，重新允许开下拉加载
                        refreshing: false, // 是否在刷新数据
                    },
                    () => {
                        this.state.dataArray.map((a: any, index: number) => {
                            if (!a['image']) {

                                setImageById(a.partyImageId).then((value: any) => {
                                    let dom = document.getElementById(a.id + '-' + index);
                                    if (dom) {
                                        dom.setAttribute('src', value);
                                    }
                                });
                            }
                        });

                        let dataSource = then.state.dataSource.cloneWithRows(this.state.dataArray);
                        then.setState({
                            dataSource,
                        });
                    }
                );
            } else {
                this.setState({
                    refreshing: false,
                    isLoading: false,
                    hasMore: false,
                });
                return false;
            }
        });
    };
    imageLoad = (image: any, index: number) => {
        this.setState((preState) => {
            const dataArray = preState.dataArray;

            dataArray[index].image = image;
            return {
                dataArray,
            };
        });
    };
    cleanList = (value: any) => {
        this.setState((preState) => {
            const dataArray = value;
            const dataSource = new ListView.DataSource({
                rowHasChanged: (row1: any, row2: any) => row1 !== row2,
            });
            return {
                dataArray,
                dataSource,
            };
        });
    };
    // 滑动到底部时加载更多
    onEndReached = (event: any) => {
        // 加载中或没有数据了都不再加载
        const offset = this.state.offset! + 1;

        if (this.state.isLoading || !this.state.hasMore) {
            return;
        }

        this.setState(
            {
                isLoading: true,
                offset,
            },
            () => {
                this.loadData();
            }
        );
    };
    row = (rowData: any, sectionID: any, rowID: string | number | undefined) => {
        const score = parseInt(rowData.score)
        const {history} = this.props
        const starNode: any = []
        for (let i = 0; i < score; i++) {
            starNode.push(
                <label style={{zoom: 0.4, float: "none", backgroundImage: 'url(/images/icons/star-x.png)'}}></label>
            )

        }
        return (

            <WingBlank size="lg">
                <WhiteSpace size="lg"/>
                <Card>
                    <Card.Header
                        title={rowData.propertyName}
                        extra={<span>{
                            rowData.stateStr
                        }</span>}
                    />
                    <Card.Body>
                        <Flex>
                            <Flex.Item style={{maxWidth: 130}}> <img src={''} style={{width: 130, height: 88}}
                                                                     id={rowData.id + '-' + rowID}></img></Flex.Item>
                            <Flex.Item>
                                <div className="act-t">
                                    <div className="activity-hint clearfix">
                      <span style={{fontSize: '18px'}}
                            onClick={() => {
                                history.push(`/party_details/${rowData.partyId}`);
                            }}
                      >{rowData.partyName}</span>
                                    </div>
                                </div>
                                <div className="act-t">
                                    <div className="activity-hint clearfix">

                                        <fieldset className="starability-slot" style={{width: '100%'}}>


                                            {
                                                starNode.map((item: any) => {
                                                    return item
                                                })
                                            }
                                        </fieldset>
                                    </div>
                                </div>
                            </Flex.Item>
                        </Flex>
                        <Flex>
                            <Flex.Item>
                                {rowData.appraisal}
                                <div id={rowData.id}>
                                    {

                                        rowData.imageIdList.length > 0 && <a onClick={() => {

                                            loadingBatchImage(rowData.imageIdList).then((res: any) => {

                                                return Modal.alert("评论图片", <Grid data={res}
                                                                                 columnNum={2}
                                                                                 renderItem={dataItem => (
                                                                                     <div
                                                                                         style={{padding: '12.5px'}}>
                                                                                         <img src={dataItem!.icon}
                                                                                              style={{
                                                                                                  width: '100px',
                                                                                                  height: '100px'
                                                                                              }} alt=""/>
                                                                                         <div style={{
                                                                                             color: '#888',
                                                                                             fontSize: '14px',
                                                                                             marginTop: '12px'
                                                                                         }}>

                                                                                         </div>
                                                                                     </div>
                                                                                 )}
                                                />)
                                            })


                                        }} style={{color: 'red'}}>
                                            点击查看图片
                                        </a>

                                    }
                                </div>
                            </Flex.Item>
                        </Flex>
                    </Card.Body>
                    <Card.Footer content={<div>评价于 {rowData.createDate}</div>}/>
                </Card>
                <WhiteSpace size="lg"/>
            </WingBlank>
        );
    };
    render() {


        return (
        <ListView
                style={{height: window.innerHeight}}
                dataSource={this.state.dataSource}
                className="am-list sticky-list"
                renderFooter={() => (
                    <div style={{padding: 30, textAlign: 'center'}}>
                        {this.state.isLoading ? '加载中...' : '加载完毕'}
                    </div>
                )}
                renderRow={(r, s, h) => this.row(r, s, h)}
                initialListSize={10}
                pageSize={10}
                onEndReachedThreshold={50}
                // renderSeparator={separator}
                renderBodyComponent={() =>   <MyBody/>}
                renderSectionBodyWrapper={() =>   <SmallBody/>}
                onEndReached={this.onEndReached}
            />
        );
    }
}

export default index;
